package com.sip.stream.utils.zfy.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.sip.stream.utils.zfy.listener.DataBindingViewHolderClickListener;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseDataBindingAdapter<M> extends RecyclerView.Adapter<BaseDataBindingViewHolder> {

    protected ArrayList<M> datasource;
    public DataBindingViewHolderClickListener<M> onClickListener;

    private BaseDataBindingAdapter() {}

    public BaseDataBindingAdapter(DataBindingViewHolderClickListener<M> dataBindingViewHolderClickListener) {
        this.onClickListener = dataBindingViewHolderClickListener;
        this.datasource = new ArrayList<>();
    }

    public ViewDataBinding getDatabindingT(ViewGroup viewGroup, int i) {
        return DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), i, viewGroup, false);
    }

    @Override
    public void onBindViewHolder(BaseDataBindingViewHolder baseDataBindingViewHolder, int i) {
        baseDataBindingViewHolder.onBindViewHolder(i, this.datasource.get(i));
    }

    public ArrayList<M> getDatasource() {
        return this.datasource;
    }

    public void clearDatasource() {
        this.datasource.clear();
    }

    public void addAll(List<M> list) {
        this.datasource.addAll(list);
    }

    public void addAllWithNotify(List<M> list) {
        int size = this.datasource.size();
        this.datasource.addAll(list);
        if (size > 0) {
            notifyItemRangeChanged(size, list.size());
        } else {
            notifyDataSetChanged();
        }
    }

    public void addWithNotify(M m) {
        int size = this.datasource.size();
        this.datasource.add(m);
        if (size > 0) {
            notifyItemRangeChanged(size, 1);
        } else {
            notifyDataSetChanged();
        }
    }

    public void addAllWithClear(List<M> list) {
        this.datasource.clear();
        addAll(list);
    }

    @Override
    public int getItemCount() {
        ArrayList<M> arrayList = this.datasource;
        if (arrayList == null) {
            return 0;
        }
        return arrayList.size();
    }
}
